<template>
  <q-page>
    <q-inner-loading visible v-if="trend.total==0">
      <q-spinner-gears size="50px" color="primary" />
      <b class="text-primary">数据加载中...</b>
    </q-inner-loading>

    <!-- header -->
    <q-toolbar color="primary">
      <q-toolbar-title></q-toolbar-title>
      <q-toolbar-title shrink>
        <span slot="subtitle" class="text-right">
          <div><b>{{trend.total}}</b>人</div>
          <div>全部用户</div>
        </span>
      </q-toolbar-title>
      <q-toolbar-title shrink>
        <span slot="subtitle" class="text-right">
          <div><b>{{trend.totalWeek}}</b>人</div>
          <div>本周新增</div>
        </span>
      </q-toolbar-title>
      <q-toolbar-title shrink>
        <span slot="subtitle" class="text-right">
          <div><b>{{trend.totalDay}}</b>人</div>
          <div>今日新增</div>
        </span>
      </q-toolbar-title>
    </q-toolbar>

    <q-infinite-scroll :handler="loadUsers" ref="scroll">
      <!-- list -->
      <q-list separator :no-border="$q.platform.is.mobile" 
        :style="$q.platform.is.desktop?'padding:8px;':''">

        <q-item style="padding:0;">
          <q-search icon="mdi-account-search" class="full-width no-shadow" :value="query" 
              inverted-light color="grey-2"
            placeholder="通过昵称及手机号过滤，按Enter后搜索更多" autofocus="true"
            @input="filterUser" @clear="searchUser('')" @change="searchUser" clearable/>
        </q-item>

        <q-collapsible v-for="item in filteredList" :key="'user_'+item.id" @show="loadUserDetail(item)">
          <template slot="header">
            <q-item-side :avatar="item.avatar" />
            <q-item-main>
              <q-item-tile label><a :href="'https://www.douban.com/people/'+item.id+'/'" target="_blank">{{item.name}}</a></q-item-tile>
              <q-item-tile sublabel>{{item.phone == '0' ? '' : item.phone}}</q-item-tile>
            </q-item-main>
            <q-item-side right v-if="$q.platform.is.desktop && item.tags.trim().length>0">
              <q-btn v-for="(tag,idx) in parseUserTags(item,3)" :key="'ut_'+item.id+idx"
                      @click.stop="tagPlayer(item)"
                      outline rounded dense>
                {{tag}}
              </q-btn>
            </q-item-side>
            <!-- action list -->
            <q-item-side right>
              <q-btn-dropdown dense outline @click.stop color="primary" label="操作">
                <!-- 下拉内容 -->
                <q-list separator class="q-pa-none" style="min-width:120px;">
                  <q-list-header>用户标签</q-list-header>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat color="primary" v-close-overlay
                        label="标记用户" @click="tagPlayer(item)" />
                  </q-item>
                  <q-item-separator />
                  <q-list-header>黑名单操作</q-list-header>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat v-close-overlay
                        label="临时请假(30天)" @click="blackPlayer(item, '临时请假', 30)" />
                  </q-item>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat v-close-overlay
                        label="无故迟到(30天)" @click="blackPlayer(item, '无故迟到', 30)" />
                  </q-item>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat v-close-overlay
                        label="低分评论(30天)" @click="blackPlayer(item, '低分评论', 30)" />
                  </q-item>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat v-close-overlay
                        label="无故缺席(90天)" @click="blackPlayer(item, '无故缺席', 90)" />
                  </q-item>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat v-close-overlay
                        label="私下转票(90天)" @click="blackPlayer(item, '私下转票', 90)" />
                  </q-item>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat v-close-overlay
                        label="虚假信息(90天)" @click="blackPlayer(item, '虚假信息', 90)" />
                  </q-item>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat v-close-overlay
                        label="态度恶劣(90天)" @click="blackPlayer(item, '态度恶劣', 90)"/>
                  </q-item>
                  <q-item class="q-pa-none">
                      <q-btn class="full-width" dense flat v-close-overlay
                          label="恶意评论(永久)"  @click="blackPlayer(item, '恶意评分', 10000)"/>
                    </q-item>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat v-close-overlay
                        label="违反礼仪(永久)"  @click="blackPlayer(item, '严重违规', 10000)"/>
                  </q-item>
                  <q-item class="q-pa-none">
                    <q-btn class="full-width" dense flat color="primary" v-close-overlay
                        label="解除限制"  @click="blackPlayer(item, '', 0)"/>
                  </q-item>
                </q-list>
              </q-btn-dropdown>
            </q-item-side>
          </template>
          <q-spinner-gears :size="30" color="primary" v-if="!item.detail" />
          <div v-if="item.detail" class="row gutter-sm">
            <div class="col-12" v-if="item.tags.trim().length>0">
              用户标签:
              <q-btn v-for="(tag,idx) in parseUserTags(item,3)" :key="'ut2_'+item.id+idx"
                      @click.stop="tagPlayer(item)" class="q-mr-md"
                      outline rounded dense>
                {{tag}}
              </q-btn>
            </div>
            <q-list class="col-xs-12 col-md-4" no-border separator>
              <q-list-header>基本信息</q-list-header>
              <q-item>
                <q-item-main label="豆瓣ID" />
                <q-item-side right>{{item.id}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="豆瓣昵称" />
                <q-item-side right>{{item.name}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="粉丝数量" />
                <q-item-side right>{{item.followers}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="所在城市" />
                <q-item-side right>{{item.cityName}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="真实姓名" />
                <q-item-side right>{{item.detail.realName}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="联系电话" />
                <q-item-side right>{{item.detail.phone}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="性别" />
                <q-item-side right>{{item.detail.gender}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="年龄" />
                <q-item-side right>{{item.detail.age}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="职业" />
                <q-item-side right>{{item.detail.job}}</q-item-side>
              </q-item>
            </q-list>
            <q-list class="col-xs-12 col-md-5" no-border separator>
              <q-list-header>活动数据</q-list-header>
              <q-item>
                <q-item-main label="报名次数" />
                <q-item-side right>{{item.detail.eventCount}}</q-item-side>
              </q-item>
              <q-item v-if="item.detail.eventPickedCount > 0">
                <q-item-main label="最近报名" />
                <q-item-side right>
                  <div v-for="(label,idx) in splitStringArray(item.detail.eventMovies, 1)" :key="item.id+'event' + idx">
                    {{label}}
                  </div>
                </q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="中奖次数" />
                <q-item-side right>{{item.detail.eventPickedCount}}</q-item-side>
              </q-item>
              <q-item v-if="item.detail.eventPickedCount > 0">
                <q-item-main label="最近中奖" />
                <q-item-side right>
                  <div v-for="(label,idx) in splitStringArray(item.detail.eventPickedMovies, 1)" :key="item.id+'picked' + idx">
                    {{label}}
                  </div>
                </q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="签到次数" />
                <q-item-side right>{{item.detail.eventCheckedCount}}</q-item-side>
              </q-item>
              <q-item>
                <q-item-main label="评论次数" />
                <q-item-side right>{{item.detail.eventRatingCount}}</q-item-side>
              </q-item>
              <q-item v-if="item.detail.eventRatingCount>0&&item.detail.eventMovieCount>0">
                <q-item-main label="评分宽容度" />
                <q-item-side right>
                  {{(item.detail.eventRatingSum/item.detail.eventRatingCount - item.detail.eventMovieSum/item.detail.eventMovieCount).toFixed(2)}}
                </q-item-side>
              </q-item>
              <q-item v-if="item.detail.eventRatingCount>0">
                <q-item-main label="评论均分" />
                <q-item-side right>{{(item.detail.eventRatingSum/item.detail.eventRatingCount).toFixed(2)}}</q-item-side>
              </q-item>
              <q-item v-if="item.detail.eventRatingCount>0&&item.detail.eventMovieCount>0">
                <q-item-main label="影片均分" />
                <q-item-side right>{{(item.detail.eventMovieSum/item.detail.eventMovieCount).toFixed(2)}}</q-item-side>
              </q-item>
            </q-list>
            <q-list class="col-xs-12 col-md-3" no-border separator>
              <q-list-header>黑历史</q-list-header>
              <q-item>
                <q-item-main label="当前状态" />
                <q-item-side right>{{computeReleaseDate(item.detail)?'拉黑':'正常'}}</q-item-side>
              </q-item>
              <q-item v-if="computeReleaseDate(item.detail)">
                <q-item-main label="解禁日期" />
                <q-item-side right>{{computeReleaseDate(item.detail).toLocaleDateString()}}</q-item-side>
              </q-item>
              <q-item v-if="item.detail.blockCause.length>0">
                <q-item-main label="黑历史" />
                <q-item-side right>
                  <div v-for="(label,idx) in splitStringArray(item.detail.blockCause, 3)" :key="item.id+'black' + idx">
                    {{label}}
                  </div>
                </q-item-side>
              </q-item>
            </q-list>
          </div>
        </q-collapsible>
        <q-spinner-gears slot="message" :size="30" color="primary" />
      </q-list>
    </q-infinite-scroll>

    <q-modal v-model="modal" :position="$q.platform.is.mobile?'':'right'" :maximized="$q.platform.is.mobile">      
      <q-toolbar>
        <q-toolbar-title color="primary">用户标签管理</q-toolbar-title>
        <q-btn flat round dense icon="mdi-close" @click="modal=false" />
      </q-toolbar>
      <q-list padding no-border>
        <q-list-header><b>{{currentUser.name}}</b>的标签</q-list-header>
        <q-item multiline>
          <q-item-main>
            <q-chips-input placeholder="输入标签后，按Enter保存" autofocus
              ref="iTag"
              v-model="currentTags" 
              @input="saveTag" />
          </q-item-main>
        </q-item>
        <q-list-header>常用用户标签</q-list-header>
        <q-item>
          <q-item-main>
            <q-btn v-for="label in ['优质', '活跃', 'VIP', '作者', '美女', '好评', '宽容', '暖男', '热心', '认真']" 
              :key="'tag_'+label"  :label="label"
              @click="addTag(label)" 
              outline rounded class="q-ma-sm" color="primary" />
          </q-item-main>
        </q-item>
        <q-item>
          <q-item-main>
            <q-btn v-for="label in ['苛刻', '操蛋', '矫情', '有病', '弱智']" 
              :key="'tag_'+label"  :label="label"
              @click="addTag(label)" 
              outline rounded class="q-ma-sm" color="black" />
          </q-item-main>
        </q-item>
      </q-list>
    </q-modal>
  </q-page>
</template>

<script>
export default {
  name: 'PageIndexUser',
  data () {
    return {
      trend: {
        total: 0,
        totalDay: 0,
        totalWeek: 0
      },
      filter: '',     
      query: '', 
      modal: false,
      currentUser: {},
      currentTags:[],

      limit: 50,
      list: [],
      ids: new Set()
    }
  },
  mounted() {
    this.$api.ui.pageTitle = '盗梦用户管理';
    this.loadUserTrend();
    this.$refs.scroll.loadMore();
  },
  methods: {
    loadUserDetail(user) {
      if(!user.detail) {
        let me = this;
        me.$api.user.loadOneUser(user.id, res=>{
          user.detail = res.data.model;
        });
      }
    },
    loadUsers(page, done) {
      let me = this;
      this.$api.user.loadUsers(me.limit*(page-1), me.limit, res=>{
        let data = res.data;
        data.model.forEach(item=>{
          if(!me.ids.has(item.id)) {
            item.detail = false;
            me.list.push(item);
            me.ids.add(item.id);
          }
        });
        done(data.model.length < me.limit);
      });
    },
    loadUserTrend() {
      let me = this;
      this.$api.user.loadUserTrend(res=>{
        me.trend = res.data.model;
      });
    },
    parseUserTags(user, limit) {
      if(user.tags && user.tags.trim().length>0) {
        let tagArray = user.tags.trim().split(',');
        if(tagArray.length > limit) {
          return tagArray.splice(0, limit);
        }
        return tagArray;
      }
      return [];
    },
    filterUser(val) {
      this.filter = val;
      // control infinte scroll
      if(this.filter.length > 0) {
        this.$refs.scroll.stop();
      } else {
        this.$refs.scroll.resume();
      }
    },
    searchUser(val) {
      if(val.trim().length > 0) {
        let me = this;
        me.$api.search.searchUser(val.trim(), res=>{
          res.data.model.forEach(item=>{
            if(!me.ids.has(item.id)) {
              item.detail = false;
              me.list.push(item);
              me.ids.add(item.id);
            }
          });
          me.query = val;
          me.filter = val;
        })
      } else {      
        this.query = val;
        this.filterUser(val);
      }
    },
    blackPlayer(user, type, days) {
      let me = this;
      this.$api.user.blockUser(user.id, type, days, res=>{
        user.detail = res.data.model;
        me.$q.notify({message: '操作成功', type: 'positive'})
      });
    },
    tagPlayer(user) {
      this.currentUser = user;
      this.currentTags = this.parseUserTags(user, 1000);
      this.$refs.iTag.focus();
      this.modal = true;
    },
    addTag(tag) {
      if(!this.currentTags.includes(tag)) {
        this.currentTags.push(tag);
        this.saveTag(this.currentTags);
      }
    },
    saveTag(newVal) {
      let me = this;
      me.currentUser.tags = this.currentTags.join(',');
      this.$api.user.tagUser(me.currentUser.id, me.currentUser.tags, res=>{});
    },
    splitStringArray(val, limit) {
      if(val && val.trim().length>0) {
        let tagArray = val.trim().split(',');
        if(tagArray.length > limit) {
          return tagArray.splice(0, limit);
        }
        return tagArray;
      }
      return [];
    },
    computeReleaseDate(detail) {
      let blockDays = detail.blockDays;
      if(blockDays<=0) {
        let cur = new Date();
        cur.setYear(2017);
        return false;
      } else {
        let blockTime = detail.blockTime;
        let time = new Date(blockTime.replace('-','/').replace('-','/').substring(0,10));
        let days = time.getDate() + blockDays;
        time.setDate(days);
        return time;
      }
    }
  },
  computed: {
    filteredList() {
      let query = this.filter.toLowerCase();
      return this.list.filter(function (user) {
        if(query.length>0) {
          if(user.name.toLowerCase().indexOf(query)>=0) {
            return true;
          }
          if(user.phone.indexOf(query)>=0) {
            return true;
          }       
          return false;
        }
        return true;
      })
    }
  }
}
</script>

<style>
main div.q-btn-inner>i:last-child {
  display:none;
}

.q-input-chips .q-chip {
  margin: 5px;
}
</style>
